﻿namespace LS.Nc6.Web.Entry.Areas.Cms.Controllers
{
    /// <summary>
    /// 内容字段设置
    /// </summary>
    [Route("[area]/[controller]/[action]")]
    [Area("Cms")]
    [ApiDescriptionSettings("Default")]
    public class TablestyleController : BaseAdminController
    {
        #region CmsTablestyleController
        private readonly ICmsTablestyleService _tablestyleService;
        private readonly ICache _cache;
        public TablestyleController(ICmsTablestyleService tablestyleService, IOptions<CacheOptions> cacheOptions, Func<string, ISingleton, object> resolveNamed)
            :base(cacheOptions, resolveNamed)
        {
            _tablestyleService = tablestyleService;
            _cache = resolveNamed(cacheOptions.Value.CacheType.ToString(), default) as ICache;
        }
        #endregion

        #region 页面
        public ActionResult Index()
        {
            SysPower(SysMenuConstant.MENU_CMS_SETTING_NRZDSZ, SysMenuConstant.FUN_SELECT, UserInfo.ID.ToString());
            return View();
        }
        public ActionResult Create(long id=0)
        {
            if (id == 0)
            {
                return ErrorCustomMsg(ResponseHelper.NONEXISTENT);
            }
                SysPower(SysMenuConstant.MENU_CMS_SETTING_NRZDSZ, SysMenuConstant.FUN_SELECT, UserInfo.ID.ToString());
            var model = new TablestyleInput();
            model.RelatedIdentity = id;
            ViewBag.InputTypeList = typeof(InputType).EnumToList();

            return View("Edit", model);
        }
        public async Task<ActionResult> Edit(long id)
        {
            SysPower(SysMenuConstant.MENU_CMS_SETTING_NRZDSZ, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString());
            var model = await _tablestyleService.GetByIdAsync(id);
            if (model == null)
            {
                return ErrorCustomMsg(ResponseHelper.NONEXISTENT);
            }
            var emodel = new TablestyleInput();
            CommonMethodHelper.MapperToModel(emodel, model, null);

            ViewBag.InputTypeList = typeof(InputType).EnumToList();

           
            //ViewBag.ItemValues = inputStyleItem.ItemValues;
            List<Hashtable> listextends = new List<Hashtable>();
            if (!string.IsNullOrEmpty(model.ExtendValues))
            {
                InputStyleItem inputStyleItem = JsonSerializer.Deserialize<InputStyleItem>(model.ExtendValues, CommonMethodHelper.MyHtmlJsonOptions);
                var JObjectNode = JsonNode.Parse(inputStyleItem.ItemValues);
                JsonArray JArray = JObjectNode.AsArray()!;

                foreach (var item in JArray)
                {
                    var JsonObject = item.AsObject()!;
                    Hashtable hs = new Hashtable();
                    hs.Add("label", JsonObject["label"].ToString());
                    hs.Add("value", JsonObject["value"].ToString());
                    hs.Add("selected", JsonObject["selected"].ToString());
                    listextends.Add(hs);
                }
                ViewBag.Height = inputStyleItem.Height;
                ViewBag.CustomizeCode = inputStyleItem.CustomizeCode;
            }
            
            ViewBag.ExtendsList = listextends;
            

            ViewBag.IsExtendHeight = (model.InputType == "TextArea" || model.InputType == "TextEditor") ? "block" : "none";
            ViewBag.IsExtendAttr = (model.InputType == "CheckBox" || model.InputType == "SelectMultiple" || model.InputType == "Radio" || model.InputType == "SelectOne") ? "block" : "none";

            return View(emodel);
        }

        public async Task<ActionResult> Rule(long id)
        {
            SysPower(SysMenuConstant.MENU_CMS_SETTING_NRZDSZ, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString());
            var model = await _tablestyleService.GetByIdAsync(id);
            if (model == null)
            {
                return ErrorCustomMsg(ResponseHelper.NONEXISTENT);
            }
            List<Hashtable> listextends = new List<Hashtable>();
            if (!string.IsNullOrEmpty(model.ExtendValues))
            {
                InputStyleItem inputStyleItem = JsonSerializer.Deserialize<InputStyleItem>(model.ExtendValues, CommonMethodHelper.MyHtmlJsonOptions);
                if(!string.IsNullOrEmpty(inputStyleItem.RuleValues))
                {
                    var JObjectNode = JsonNode.Parse(inputStyleItem.RuleValues);
                    JsonArray JArray = JObjectNode.AsArray()!;

                    foreach (var item in JArray)
                    {
                        var JsonObject = item.AsObject()!;
                        Hashtable hs = new Hashtable();
                        hs.Add("type", JsonObject["type"].ToString());
                        hs.Add("value", JsonObject["value"].ToString());
                        hs.Add("message", JsonObject["message"].ToString());
                        listextends.Add(hs);
                    }
                }
            }

            ViewBag.ExtendsList = listextends;

            //ViewBag.ValidateTypeList = typeof(ValidateType).EnumToList();
            ViewBag.ValidateTypeJson = JsonSerializer.Serialize( typeof(ValidateType).EnumToList(),CommonMethodHelper.MyJsonOptions);
            return View(model);  
        }
        #endregion

        #region  公共方法
        [HttpGet]
        public async Task<ResponseResultDataList> GetList()
        {
            string channelId = RequestHelper.FilterParam(Request.Query["channelId"]);
            var page = Request.Query["page"].ToString().GetQueryValueOrNull<int>(1);
            var limit = Request.Query["limit"].ToString().GetQueryValueOrNull<int>(50);
            string field = Request.Query["field"];
            string order = Request.Query["order"];

            var expable = Expressionable.Create<CmsTablestyleEntity>();
            expable.AndIF(!string.IsNullOrEmpty(channelId), a => a.RelatedIdentity == channelId.ParseToLong());
            var exp = expable.ToExpression();
            var strField = RequestHelper.FilterParam(field);
            var strOrder = RequestHelper.FilterParam(order);

            Expression<Func<CmsTablestyleEntity, object>> expressionOrder;
            if (string.IsNullOrEmpty(strField) || string.IsNullOrEmpty(strOrder))
            {
                expressionOrder = (a) => new { a.Id };
            }
            else
            {
                //实现字段排序
                expressionOrder = (a) => new { a.Taxis };
            }
            var result = await _tablestyleService.PageList(exp, page, limit, expressionOrder);
            return new ResponseResultDataList { code = ResponseHelper.SEUCCESSCODE, message = "请求成功", data = result.Items, count = result.TotalCount };
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SaveData([FromBody] TablestyleInput input)
        {
            bool power = true;
            if (await _tablestyleService.ExistsName(input.Id, input.RelatedIdentity.Value, input.AttributeName))
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_BMYCZ);
            }

            long result = 0;
            if (input.Id > 0)
            {
                power = SysPower(SysMenuConstant.MENU_CMS_SETTING_NRZDSZ, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                var editmodel = await _tablestyleService.GetByIdAsync(input.Id);
                CommonMethodHelper.MapperToModel(editmodel, input, null);
                if (!string.IsNullOrEmpty(editmodel.ExtendValues))
                {
                    InputStyleItem inputStyleItem = JsonSerializer.Deserialize<InputStyleItem>(editmodel.ExtendValues, CommonMethodHelper.MyHtmlJsonOptions);
                    inputStyleItem.ItemValues = input.ItemValues;
                    editmodel.ExtendValues = JsonSerializer.Serialize<InputStyleItem>(inputStyleItem, CommonMethodHelper.MyHtmlJsonOptions);
                }
                //var inputstyle = new InputStyleItem { ItemValues = input.ItemValues, RuleValues = "", Height = input.Height, CustomizeCode = "" };
                
                result = await _tablestyleService.UpdateAsync(editmodel);
            }
            else
            {
                power = SysPower(SysMenuConstant.MENU_CMS_SETTING_NRZDSZ, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                var model = new CmsTablestyleEntity();
                CommonMethodHelper.MapperToModel(model, input, null);
                var inputstyle = new InputStyleItem { ItemValues = input.ItemValues, RuleValues = "[]", Height = input.Height, CustomizeCode = "" };
                model.ExtendValues = JsonSerializer.Serialize<InputStyleItem>(inputstyle, CommonMethodHelper.MyHtmlJsonOptions);
                result = await _tablestyleService.InsertAsync(model);
            }
            return ResponseHelper.SaveResult(result);
        }

        /// <summary>
        /// 保存规则
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SaveRule([FromBody] TableStyleRuleInput input)
        {
            bool power = true;
            long result = 0;
            if (input.Id > 0)
            {
                power = SysPower(SysMenuConstant.MENU_CMS_SETTING_NRZDSZ, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                var editmodel = await _tablestyleService.GetByIdAsync(input.Id);
                CommonMethodHelper.MapperToModel(editmodel, input, null);
                if (!string.IsNullOrEmpty(editmodel.ExtendValues))
                {
                    InputStyleItem inputStyleItem = JsonSerializer.Deserialize<InputStyleItem>(editmodel.ExtendValues, CommonMethodHelper.MyHtmlJsonOptions);
                    inputStyleItem.RuleValues = input.StyleRules;
                    editmodel.ExtendValues = JsonSerializer.Serialize<InputStyleItem>(inputStyleItem, CommonMethodHelper.MyHtmlJsonOptions);
                }

                result = await _tablestyleService.UpdateAsync(editmodel);
            }
            return ResponseHelper.SaveResult(result);
        }


        [HttpPost]
        public async  Task<ResponseResult> Delete([FromBody]DeletDataInput input)
        {
            var r = SysPower(SysMenuConstant.MENU_CMS_SETTING_NRZDSZ, SysMenuConstant.FUN_DELETE, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_WSCQX);
            }
            if (string.IsNullOrEmpty(input.Ids))
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            int result =await _tablestyleService.DeleteAsync(input.Ids.ToString());
            return ResponseHelper.DeleteResult(result);
        }

        #endregion


        #region 私有方法

     
        #endregion
    }
}